package pack4;

import java.util.Stack;

class Solution5 {
    public int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < asteroids.length; i++) {
            if (asteroids[i] > 0) {
                stack.push(asteroids[i]);
            } else {
                while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < Math.abs(asteroids[i])) {
                    stack.pop();
                }

                if (stack.isEmpty() || stack.peek() < 0) {
                    stack.push(asteroids[i]);
                } else if (stack.peek() == Math.abs(asteroids[i])) {
                    stack.pop();
                }
            }
        }

        int[] result = new int[stack.size()];
        int index = result.length - 1;
        while (!stack.isEmpty()) {
            result[index] = stack.pop();
            index--;
        }
        return result;
    }

    public static void main(String[] args) {
        Solution5 solution = new Solution5();
        int[] asteroids1 = {5, 10, -5};
        int[] asteroids2 = {8, -8};
        int[] asteroids3 = {10, 2, -5};

        System.out.print("示例1: "+"[");
        int[] result1 = solution.asteroidCollision(asteroids1);
        for (int i = 0; i < result1.length; i++) {
            if(i>0)
                System.out.print(",");
            System.out.print(result1[i]);
        }
        System.out.println("]");

        System.out.print("示例2: "+"[");
        int[] result2 = solution.asteroidCollision(asteroids2);
        for (int i = 0; i < result2.length; i++) {
            if(i>0)
                System.out.print(",");
            System.out.print(result2[i]);
        }
        System.out.println("]");

        System.out.print("示例3: "+"[");
        int[] result3 = solution.asteroidCollision(asteroids3);
        for (int i = 0; i < result3.length; i++) {
            if(i>0)
                System.out.print(",");
            System.out.print(result3[i]);
        }
        System.out.println("]");
    }
}